import * as env from "@env"
import * as sys from "@sys"
import * as sciter from "@sciter"
import defaultLang from "./lang"

const view = Window.this

function parseLang() {
    let exist = null
    let langData = null

    function getLangData() {
        if (exist !== null) {
            return
        }
        const fs = sys.fs
        try {
            let appPath = view.xcall("current_path")
            let lang = env.language() + ".json"
            let files = fs.$readdir(appPath + "/lang")
            for (let file of files) {
                if (file.type === 1 && lang === file.name) {
                    exist = true
                    break
                }
            }
            if (exist) {
                let data = fs.$readfile(appPath + "/lang" + "/" + lang)
                data = sciter.decode(data, "utf-8")
                try {
                    return JSON.parse(data)
                } catch (e) {
                    return null
                }
            }
            return null
        } catch (e) {

        }
    }

    return () => {
        if (exist === null) {
            langData = getLangData()
        }
        if (langData == null) {
            return
        }
        return langData
    }
}

const langData = parseLang()()
const loading = (() => {
    let loading
    return function () {
        return {
            show() {
                if (!loading) {
                    loading = document.createElement("div")
                    loading.id = "_loading_id"
                    loading.style.position = "absolute"
                    loading.style.left = "0"
                    loading.style.top = "30px"
                    loading.style.zIndex = "99999999999"
                    loading.style.width = "100%"
                    loading.style.height = "100%"
                    loading.style.backgroundColor = "#ffffffdd"
                    loading.style.flow = "horizontal"
                    loading.style.verticalAlign = "middle"
                    loading.style.horizontalAlign = "center"
                    loading.innerHTML = "<img src='/images/icon/loading.gif' width='30px' height='30px'>"
                }
                try {
                    document.body.removeChild(document.querySelector("#_loading_id"))
                    document.body.removeChild(loading)
                } catch (e) {
                }
                document.body.append(loading)
            },
            hide() {
                try {
                    document.body.removeChild(document.querySelector("#_loading_id"))
                    document.body.removeChild(loading)
                    loading = null
                } catch (e) {
                    loading = null
                }
            }
        }
    }
})()()
export default {
    sys,
    /**
     * 系统语言
     * @param key {string} 语言文件的key
     */
    lang(key) {
        let script
        let val
        try {
            script = "langData." + key
            val = eval(script)
        } catch (e) {
            val = undefined
        }
        if (val === undefined) {
            script = "defaultLang." + key
            val = eval(script)
        }
        return val
    },
    /**
     * 返回数据类型
     * @param val {*}
     * @returns {string}
     */
    valType(val) {
        return Object.prototype.toString.call(val).slice(8, -1)
    },
    /**
     * 判断路径是不是存在
     * @param path
     */
    isPathExist(path) {
        const stat = sys.fs.$stat(path)
        if (stat) {
            return stat
        } else {
            return false
        }
    }
    ,
    /**
     * 返回app数据目录
     * @returns {string}
     */
    userAppDataDir() {
        return env.path("USER_APPDATA")
    }
    ,
    /**
     * 用户根目录
     * @returns {*}
     */
    userHomeDir() {
        return env.path("USER_HOME")
    }
    ,
    /**
     * 返回桌面工作区域
     * @returns [width,height]
     */
    workAreaSize() {
        return view.screenBox("workarea", "dimension")
    }
    ,
    /**
     * 返回窗口位置
     * @returns {[x,y]}
     */
    windowPosition() {
        let [x, y] = view.box("position", "border", "screen")
        return [x, y]
    }
    ,
    /**
     * 移动到中心
     */
    moveToCenter() {
        const [w, h] = this.windowSize()
        const [width, height] = this.workAreaSize()
        view.move(width / 2 - w / 2, height / 2 - h / 2, w, h)
        this.focus()
    }
    ,
    /**
     * 设置到最顶层
     */
    setTopmost() {
        view.isTopmost = true
    }
    ,
    /**
     * 获取窗口尺寸
     * @returns [width,height]
     */
    windowSize() {
        return view.box("dimension", "border")
    }
    ,
    /**
     * 聚个焦
     */
    focus() {
        view.isTopmost = true
        setTimeout(() => {
            view.isTopmost = false
        }, 10)
    }
    ,
    /**
     * 打印
     * @param args
     */
    log(...args) {
        try {
            let val = args.map(e => JSON.stringify(e))
            console.log(...val)
        } catch (e) {
            console.log("tools.log err", e.toString())
        }
    }
    ,
    /**
     * 显示窗口
     */
    windowShow() {
        view.state = Window.WINDOW_SHOWN
    }
    ,
    /**
     * 隐藏窗口
     */
    windowHide() {
        view.state = Window.WINDOW_HIDDEN
    }
    ,
    /**
     * 关闭窗口
     */
    windowClose(data) {
        view.close(data || "close")
    }
    ,
    /**
     * 获取视图Window.this
     * @returns {*}
     */
    getView() {
        return view
    },
    xcall(...args) {
        return view.xcall(...args)
    },
    /**
     * 获取传递过来的参数
     * @returns {*}
     */
    getParameters() {
        return view.parameters
    }
    ,
    /**
     * 发送全局事件
     * @param name {string} 事件名称
     * @param data {*} 分发的数据
     */
    dispatchGlobalEvt(name, data) {
        view.xcall("global_event", name, data || "")
    }
    ,
    /**
     * 绑定全局事件
     * @param name {string} 事件名称
     * @param handler {Function} 回调方法
     */
    bindGlobalEvt(name, handler) {
        document.onGlobalEvent(name, (...args) => {
            handler(...args)
        })
    }
    ,
    /**
     * 自定义alert提示框
     * @param msg {string} 提示消息
     * @param obj {object} 参数 {type:{string|[normal,info,success,error,warning]} ,title}
     * @returns {*}
     */
    alert(msg, obj) {
        let [x, y] = this.windowPosition()
        let [w, h] = this.windowSize()
        const {title, type} = obj || {}
        return new Promise(resolve => {
            setTimeout(() => {
                let modal = view.modal({
                    width: 240,
                    height: 180,
                    x: x + w / 2 - 120,
                    y: y + h / 2 - 90,
                    url: "/dialog/alert.html",
                    parameters: {
                        title,
                        msg,
                        type
                    }
                })
                resolve(modal)
            })
        })
    }
    ,
    /**
     * 自定义询问提示框
     * @param msg {string} 提示消息
     * @param obj {object} 参数 {type:{string|[normal,info,success,error,warning]} ,title}
     * @returns {*}
     */
    confirm(msg, obj) {
        let [x, y] = this.windowPosition()
        let [w, h] = this.windowSize()
        const {title, type} = obj || {}
        return new Promise(resolve => {
            setTimeout(() => {
                let modal = view.modal({
                    width: 240,
                    height: 180,
                    x: x + w / 2 - 120,
                    y: y + h / 2 - 90,
                    url: "/dialog/confirm.html",
                    parameters: {
                        title,
                        msg,
                        type
                    }
                })
                resolve(modal)
            })
        })
    },
    loading
}